package com.javaweb.newservlelt;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * LoginServlet for login request.
 * there are two ways for configuring servlet
 *  A. in web.xml
 *  B. @WebServlet
 */

@WebServlet( "/test/ratingByJson")
public class RatingAjaxJSONServlet extends HttpServlet {
    private Logger logger = LogManager.getLogger(RatingAjaxJSONServlet.class) ;
    /**
     *  Mapper tool from Jackson for serializing to and parsing from json string.
     */
    static ObjectMapper Mapper = new ObjectMapper( ) ;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp) ;
    }
    /**
     * override doPost logic from father by our own business logic
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // the request string format:  rating=xxx&comment=xxxx
        req.setCharacterEncoding("utf-8");
        String requestString = readRequestString(req) ;
        // in reality, class parameter should be a VO class.
        Map<String, String> requestData = Mapper.readValue(requestString, Map.class) ;

        String rating = requestData.get("rating") ;
        String comment = requestData.get("comment") ;
        logger.debug("got parameters: {} {}", rating, comment) ;

        requestData.put("msg", "data transferring in JSON.") ;
        /*
        Key step: set contentType to application/json, charset
         */
        resp.setContentType("application/json; charset=utf-8");
        PrintWriter out = resp.getWriter() ;
        // serializing a map object to a json string
        String retJsonString = Mapper.writeValueAsString(requestData) ;
        out.print(retJsonString) ;
        out.flush() ;
    }

    /**
     * Read data string from request body.
     * For GET request, the method of 'getParameter' could read parameter from request, however, it did not work
     * for POST request.
     * @param req
     * @return
     * @throws Exception
     */
    private String readRequestString(HttpServletRequest req) throws IOException {

        BufferedReader reader = req.getReader() ;
        String line ;
        StringBuilder stringBuilder = new StringBuilder() ;
        while ((line = reader.readLine()) != null ) {
            stringBuilder.append(line) ;
        }
        return stringBuilder.toString() ;



    }



}





